#!/bin/bash

# KWDB Java SDK Benchmark Script
# Usage: ./bench-java.sh [quick|full|compare]

set -e

SCRIPT_DIR=$(dirname "$0")
PROJECT_DIR="$SCRIPT_DIR/../../sdk-java"

cd "$PROJECT_DIR"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo -e "${GREEN}=====================================${NC}"
echo -e "${GREEN} KWDB Java SDK Benchmark Runner${NC}"
echo -e "${GREEN}=====================================${NC}"
echo

MODE="${1:-quick}"

case $MODE in
  quick)
    echo -e "${YELLOW}Running quick benchmark (10s duration)...${NC}"
    ./gradlew runBench -DbenchArgs="--transport=grpc --threads=4 --batch=500 --lingerMs=10 --duration=10s --warmup=5s"
    echo
    ./gradlew runBench -DbenchArgs="--transport=ilp --threads=4 --batch=500 --lingerMs=10 --duration=10s --warmup=5s"
    echo
    ./gradlew runBench -DbenchArgs="--transport=jdbc --threads=4 --batch=500 --lingerMs=0 --duration=10s --warmup=5s"
    ;;

  full)
    echo -e "${YELLOW}Running full benchmark matrix (this will take ~30 minutes)...${NC}"
    ./gradlew runBenchMatrix
    ;;

  compare)
    echo -e "${YELLOW}Running benchmark comparison...${NC}"
    ./gradlew runBenchCompare
    ;;

  custom)
    shift
    echo -e "${YELLOW}Running custom benchmark with args: $@${NC}"
    ./gradlew runBench -DbenchArgs="$@"
    ;;

  *)
    echo "Usage: $0 [quick|full|compare|custom <args>]"
    echo ""
    echo "Modes:"
    echo "  quick   - Quick benchmark with 10s duration for each transport"
    echo "  full    - Full matrix test (9 configurations × 3 transports)"
    echo "  compare - Run full matrix and generate comparison report"
    echo "  custom  - Run with custom arguments"
    echo ""
    echo "Custom example:"
    echo "  $0 custom --transport=grpc --threads=8 --batch=1000 --duration=60s"
    exit 1
    ;;
esac

echo
echo -e "${GREEN}Benchmark complete!${NC}"

# Show latest results location if full or compare mode
if [ "$MODE" = "full" ] || [ "$MODE" = "compare" ]; then
  LATEST_DIR=$(ls -td docs/bench/results/*/ 2>/dev/null | head -1)
  if [ -n "$LATEST_DIR" ]; then
    echo -e "${GREEN}Results saved to: ${LATEST_DIR}bench.csv${NC}"

    # Show summary if CSV exists
    CSV_FILE="${LATEST_DIR}bench.csv"
    if [ -f "$CSV_FILE" ]; then
      echo
      echo "Summary of results:"
      echo "-------------------"

      # Count lines (excluding header)
      TOTAL_RUNS=$(($(wc -l < "$CSV_FILE") - 1))
      echo "Total benchmark runs: $TOTAL_RUNS"

      # Extract best throughput for each transport
      echo
      echo "Best throughput by transport:"
      for transport in grpc ilp jdbc; do
        BEST=$(awk -F',' -v t="$transport" '$3==t {print $9}' "$CSV_FILE" | sort -rn | head -1)
        if [ -n "$BEST" ]; then
          echo "  $transport: $BEST points/s"
        fi
      done
    fi
  fi
fi